//
//  XJEmojiViewToolBar.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/27.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

enum XJEmojiType: Int {

    case Recent = 0, Default, Emoji, Lxh
}

class XJEmojiViewToolBar: UIStackView {
    
    //记录选中的按钮
    var selectedBtn: UIButton?
    
    // 提供给外界设置当前选中按钮index的方法
    var selectSection: Int = 0 {
        
        didSet{
            
            let btn = viewWithTag(selectSection) as! UIButton
//            print(selectedBtn)
            if btn != selectedBtn {
                btn.selected = true
                selectedBtn?.selected = false
                selectedBtn = btn
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        tag = -1
        
        distribution = .FillEqually
        addChildBtn("最近", imageName: "compose_emotion_table_left", type: .Recent)
        addChildBtn("默认", imageName: "compose_emotion_table_mid", type: .Default)
        addChildBtn("Emoji", imageName: "compose_emotion_table_mid", type: .Emoji)
        addChildBtn("浪小花", imageName: "compose_emotion_table_right", type: .Lxh)
        
        
    }
    /// 点击表情类型执行闭包
    var emotionBtnClickClosure: ((type: XJEmojiType)->())?
    
    /**
     添加按钮公共方法
     */
    private func addChildBtn(title: String, imageName: String, type: XJEmojiType){
    
        let btn = UIButton()
        btn.tag = type.rawValue
        btn.addTarget(self, action: "didClickEmojiToolBarBtn:", forControlEvents: .TouchUpInside)
        
        //按钮文字及大小
        btn.setTitle(title, forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        //按钮文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        
        //按钮背景色
        btn.setBackgroundImage(UIImage(named: "\(imageName)_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "\(imageName)_selected"), forState: .Selected)
        
        addArrangedSubview(btn)
    
    }
    
    /**
     点击emojiToolBar按钮调用方法
     */
    @objc private func didClickEmojiToolBarBtn(btn: UIButton) {
    
        //如果点击的是当前选中的按钮则不执行
        if selectedBtn == btn{
            return
        }
        emotionBtnClickClosure?(type: XJEmojiType(rawValue: btn.tag)!)
        
        //取消之前选中的按钮
        selectedBtn?.selected = false
        
        //选中当前按钮
        btn.selected = true
        
        //重新记录选中按钮
        selectedBtn = btn
    
    }

}
